package com.ruoyi.gis.service.impl;

import com.ruoyi.base.domain.BusWaterSegment;
import com.ruoyi.base.mapper.BusWaterSegmentMapper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gis.domain.DrinkWaterItemData;
import com.ruoyi.gis.domain.DrinkWaterLevelData;
import com.ruoyi.gis.domain.DrinlWaterItemListData;
import com.ruoyi.gis.mapper.GisMapper;
import com.ruoyi.gis.service.IGisService;
import com.ruoyi.pwk.domain.BusPwkRhoutfall;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GisService implements IGisService {

    @Autowired
    private GisMapper gisMapper;
    @Autowired
    private BusWaterSegmentMapper busWaterSegmentMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 获取断面水质状况
     *
     * @param isdrink
     * @param ismanual
     * @param isauto
     * @return
     */
    @Override
    public List<BusWaterSegment> WaterSegmentlist(String isdrink, String ismanual, String isauto, String riverid, String countyCode) {
        List<Map<String, Object>> valuateList = new ArrayList<>();
        //自动站
        if ("1".equals(isauto)) {
            //水源地
            if ("1".equals(isdrink)) {
                //自动水源地
                valuateList = gisMapper.getDrinkWaterSegmentData(riverid, countyCode);
            } else {
                //自动地表水
                valuateList = gisMapper.getAutoWaterSegmentData(riverid, countyCode);
            }
        }
        //手工站
        if ("1".equals(ismanual)) {
            //水源地
            if ("1".equals(isdrink)) {
                //手工水源地
                valuateList = gisMapper.getManualDrinkSegmentData(riverid, countyCode);
            } else {
                //手工地表水
                valuateList = gisMapper.getManualWaterSegmentData(riverid, countyCode);
            }
        }

        List<BusWaterSegment> list = gisMapper.WaterSegmentlist(isdrink, ismanual, isauto, riverid, countyCode);
        for (BusWaterSegment busWaterSegment : list) {
            String segmentId = busWaterSegment.getId();

            List<Map<String, Object>> segmentList = valuateList.stream().filter(s -> String.valueOf(s.get("segmentId")).equals(segmentId)).collect(Collectors.toList());
            String isOverStandard = "0";
            String isOverStandardName = "达标";
            int qualityLevel = 0;
            String qualityLevelName = "无类别";
            String sampleTime = "";
            if (StringUtils.isNotEmpty(segmentList) && segmentList.size() > 0) {
                isOverStandard = String.valueOf(segmentList.get(0).get("isOverStandard"));
                isOverStandardName = String.valueOf(segmentList.get(0).get("isOverStandardName"));
                qualityLevel = Integer.parseInt(String.valueOf(segmentList.get(0).get("qualityLevel")));
                qualityLevelName = String.valueOf(segmentList.get(0).get("qualityLevelName"));
                sampleTime = String.valueOf(segmentList.get(0).get("sampleTime"));
            }
            busWaterSegment.setIsOverStandard(isOverStandard);
            busWaterSegment.setIsOverStandardName(isOverStandardName);
            busWaterSegment.setQualityLevel(qualityLevel);
            busWaterSegment.setQualityLevelName(qualityLevelName);
            busWaterSegment.setSampleTime(sampleTime);
        }

        return list;
    }

    /**
     * 获取断面评价数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> DrinkWaterTopLevelData(String id) {
        Map<String, Object> map = new HashMap<>();
        //获取断面数据
        BusWaterSegment busWaterSegment = busWaterSegmentMapper.selectBusWaterSegmentByID(id);
        map.put("busWaterSegment", busWaterSegment);
        //获取断面最新一条评价数据
        DrinkWaterLevelData segmenttopLevedata = gisMapper.selectSegmentTargetLevel(id);
        if (segmenttopLevedata != null && segmenttopLevedata.getSampledate() != null) {
            Date sampledata = segmenttopLevedata.getSampledate();
            //获取断面最新监测数据
            List<DrinkWaterItemData> segmentitemList = gisMapper.selectSegmentItemData(id, DateUtils.getFirstDayOfMonth(sampledata), DateUtils.getLastDayOfMonth(sampledata));
            segmenttopLevedata.setWateritemdata(segmentitemList);
        }
        map.put("segmenttopLevel", segmenttopLevedata);
        return map;
    }

    /**
     * 获取断面因子数据
     *
     * @param segmentId
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public Map<String, Object> DrinkWaterItemListByTime(String segmentId, String itemCode, String beginDate, String endDate) {
        //根据时间查询一段时间因子数据
        Map<String, Object> segmentItemList = new HashMap<>();
        if (segmentId != null && !"".equals(segmentId)) {
            if (itemCode != null && !"".equals(itemCode)) {
                //查询当前断面数据
                Map<String, Object> SegmentDatamap = new HashMap<>();
                SegmentDatamap.put("beginTime", beginDate);
                SegmentDatamap.put("endTime", endDate);
                SegmentDatamap.put("itemCode", itemCode);
                SegmentDatamap.put("segmentId", segmentId);
                List<DrinlWaterItemListData> manualSegmentDatalist = new ArrayList<>();
                manualSegmentDatalist = gisMapper.getManualSegmentDatamon(SegmentDatamap);

                List<Map<String, Object>> listdata = new ArrayList<>();

                // 接受所获取的时间
                List<String> timeList = new ArrayList<>();
                //返回所有月份
                timeList = DateUtils.getMonthBetweenDate(String.valueOf(beginDate), String.valueOf(endDate));
                if (timeList != null && timeList.size() > 0) {
                    for (String time : timeList) {
                        //本断面的数据处理 以时间进行分组
                        List<DrinlWaterItemListData> timeDatalist = new ArrayList<>();
                        if (manualSegmentDatalist != null && manualSegmentDatalist.size() > 0) {
                            //分组判断，stream流 根据时间进行分组
                            Map<String, List<DrinlWaterItemListData>> sunmapsSegmentID =
                                    manualSegmentDatalist.stream().collect(
                                            Collectors.groupingBy(item -> item.getSampledate())
                                    );
                            timeDatalist = sunmapsSegmentID.get(time);
                        }
                        if (timeDatalist != null && timeDatalist.size() > 0) {
                            for (DrinlWaterItemListData datavalue : timeDatalist) {
                                Map<String, Object> mapdata = new HashMap<>();
                                mapdata.put("segmentName", datavalue.getSegmentname());
                                mapdata.put("itemCode", itemCode);
                                mapdata.put("standardValue", datavalue.getStandardvalue());
                                mapdata.put("dataSegmentType", "本断面");
                                mapdata.put("sampleDate", time);
                                mapdata.put("yearSampleDate", datavalue.getYearsampledate());
                                mapdata.put("monSampleDate", datavalue.getMonsampledate());
                                mapdata.put("avgEffectiveValue", "");
                                mapdata.put("segmentID", datavalue.getSegmentid());
                                mapdata.put("qualityLevel", "");
                                mapdata.put("qualityLevelName", "");
                                mapdata.put("targetlevel", datavalue.getTargetlevel());
                                mapdata.put("targetlevelname", datavalue.getTargetlevelname());
                                mapdata.put("unit", datavalue.getUnit());
                                BigDecimal effectivevalue = datavalue.getAvgeffectivevalue();
                                DecimalFormat df = new DecimalFormat("###.#####");
                                String evalue = df.format(effectivevalue);
                                mapdata.put("effectiveValue", evalue);
                                listdata.add(mapdata);
                            }
                        }
                    }
                }
                segmentItemList.put("list", listdata);
            }
        }
        return segmentItemList;
    }

    @Override
    public List<BusPwkRhoutfall> rhOutFall(String riverid, String countyCode) {
        return gisMapper.rhOutFall(riverid, countyCode);
    }

    @Override
    public Map<String, Object> getdrinkwaterprotectinfo() {
        return gisMapper.getdrinkwaterprotectinfo();
    }

    @Override
    public List<Map<String, Object>> getdrinkwaterqualityinfo() {
        //获取水质等级
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("water_quality_level");
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataList(sysDictData);
        //获取最新监测时间
        Date newsampledate = gisMapper.getmaxsampledate("CBF8");
        //获取最新水质等级数据
        List<Map<String, Object>> waterdata = gisMapper.getdrinkwaterqualityinfo(DateUtils.getFirstDayOfMonth(newsampledate), DateUtils.getLastDayOfMonth(newsampledate));
        //获取环比水质等级数据
        List<Map<String, Object>> prevwaterdata = gisMapper.getdrinkwaterqualityinfo(DateUtils.getFirstDayOfMonth(DateUtils.addMonths(newsampledate, -1)), DateUtils.getLastDayOfMonth(DateUtils.addMonths(newsampledate, -1)));
        //获取同比水质等级数据
        List<Map<String, Object>> yearwaterdata = gisMapper.getdrinkwaterqualityinfo(DateUtils.getFirstDayOfMonth(DateUtils.addYears(newsampledate, -1)), DateUtils.getLastDayOfMonth(DateUtils.addYears(newsampledate, -1)));
        //返回数据存放
        List<Map<String, Object>> waterquality = new ArrayList<>();
        //循环水质等级数据
        Map<String, Object> waterqualitydata = new HashMap<>();
        long allcount = waterdata.size();
        long dbcount = waterdata.stream().filter(item -> !String.valueOf(item.get("isOverStandard")).equals("1")).count();
        Map<String, Object> qualityrate = new HashMap<String, Object>();
        qualityrate.put("qualityrate", allcount == 0 ? 0 : new BigDecimal(dbcount)
                .multiply(new BigDecimal(100))
                .divide(new BigDecimal(allcount), 2, BigDecimal.ROUND_HALF_UP));
        waterquality.add(qualityrate);
        for (SysDictData data : sysDictDataList) {
            long count = waterdata.stream().filter(item -> String.valueOf(item.get("qualityLevel")).equals(data.getDictValue())).count();
            waterqualitydata.put(data.getDictLabel() + "count", count);
            // 修复：使用BigDecimal进行精确计算并保留两位小数
            waterqualitydata.put(data.getDictLabel() + "rate", allcount == 0 ? 0 : new BigDecimal(count)
                    .multiply(new BigDecimal(100))
                    .divide(new BigDecimal(allcount), 2, BigDecimal.ROUND_HALF_UP));
        }
        waterquality.add(waterqualitydata);

        long prevallcount = prevwaterdata.size();
        long prevcount = prevwaterdata.stream().filter(item -> !String.valueOf(item.get("isOverStandard")).equals("1")).count();
        Map<String, Object> prevqualityrate = new HashMap<String, Object>();
        prevqualityrate.put("prevqualityrate", prevallcount == 0 ? 0 : new BigDecimal(prevcount)
                .multiply(new BigDecimal(100))
                .divide(new BigDecimal(prevallcount), 2, BigDecimal.ROUND_HALF_UP));
        waterquality.add(prevqualityrate);
        long yearallcount = yearwaterdata.size();
        long yearcount = yearwaterdata.stream().filter(item -> !String.valueOf(item.get("isOverStandard")).equals("1")).count();
        Map<String, Object> yearqualityrate = new HashMap<String, Object>();
        yearqualityrate.put("yearqualityrate", yearallcount == 0 ? 0 : new BigDecimal(yearcount)
                .multiply(new BigDecimal(100))
                .divide(new BigDecimal(yearallcount), 2, BigDecimal.ROUND_HALF_UP));
        waterquality.add(yearqualityrate);
        return waterquality;
    }

    @Override
    public List<Map<String, Object>> getdrinkwatercountyinfo() {
        List<Map<String, Object>> list = gisMapper.getdrinkwatercountyinfo();
        long allcount = list.stream().mapToLong(item -> Long.parseLong(item.get("count").toString())).sum();
        for (Map<String, Object> map : list){
            map.put("rate", allcount == 0 ? 0 : ((Long.parseLong(map.get("count").toString()) / allcount) * 100));
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getdrinkwaterregioninfo() {
        List<Map<String, Object>> list =  gisMapper.getdrinkwaterregioninfo();
        return list;
    }

    @Override
    public Map<String, Object> getRhoutSurvey() {
        int roufallNum= gisMapper.getRhoutSurvey();
        Map<String, Object> retMap=new HashMap<>();
        retMap.put("rhoutFallNums",roufallNum);
        return retMap;
    }

    @Override
    public List<Map<String, Object>> getRhoutBroadHeading(String type) {
        List<Map<String,Object>>  rhoutBroadHeading=new ArrayList<>();
        Map<String,Object> mapas1 =new HashMap<>();
//河流下的所有子河流

        if("2".equals(type)){//大类区分
            rhoutBroadHeading= gisMapper.getRhoutBroadHeading();
        }else {//小类区分
            rhoutBroadHeading= gisMapper.getRhoutSubclass();
        }
        int nums=0;
        if(rhoutBroadHeading!=null&&rhoutBroadHeading.size()>0){
            DecimalFormat df = new DecimalFormat("0.00");
            for(Map<String,Object> map:rhoutBroadHeading){
                if(StringUtils.isNotNull(map.get("outfallCode")) && StringUtils.isNotNull(map.get("outfallName"))){
                    nums=nums+ Integer.parseInt(map.get("nums").toString());
                }

            }
            for(Map<String,Object> map:rhoutBroadHeading){
                if(StringUtils.isNotNull(map.get("outfallCode")) && StringUtils.isNotNull(map.get("outfallName"))){
                    int total=Integer.parseInt(map.get("nums").toString());
                    map.put("proportion",new BigDecimal(((double) total/nums)*100).setScale(2,BigDecimal.ROUND_HALF_UP));
                    map.put("totalNum",nums);
                }
            }
            //判断是否百分比是否100%
            //先按照数据排序
            List<Map<String,Object>> sortList = rhoutBroadHeading.stream().sorted(Comparator.comparing((Map s)->Double.parseDouble(s.get("proportion").toString()))).collect(Collectors.toList());
            double zby=100;//剩余占比
            int times=0;
            for(Map<String,Object> maps:sortList){
                double warnProportion=Double.parseDouble(maps.get("proportion").toString());
                int numssize=Integer.parseInt(maps.get("nums").toString());
                times=times+1;
                if(times==sortList.size()){
                    //判断
                    if(numssize==0){
                        maps.put("proportion",0);
                    }else{
                        maps.put("proportion",new BigDecimal(zby).setScale(2,BigDecimal.ROUND_HALF_UP));
                    }
                }else{
                    zby=zby-warnProportion;
                    zby=Double.valueOf(df.format(zby));
                }
            }
            rhoutBroadHeading=sortList;
        }



        return  rhoutBroadHeading;
    }

    @Override
    public Map<String, Object> getRhoutFallType(String type) {
        Map<String, Object> retMap=new HashMap<>();
        List<Map<String,Object>>  rhoutDistributionList=gisMapper.getRhoutDistribution();
        List<Map<String, Object>> retList=new ArrayList<>();
        List<String> nameList=new ArrayList<>();
        if("1".equals(type)){//河流
            Map<String,List<Map<String,Object>>>  rhoutDistributionCol=rhoutDistributionList.stream().collect(Collectors.groupingBy(s->String.valueOf(s.get("outfallfirstclassifycode"))));
            for(String outfallTypeCode:rhoutDistributionCol.keySet()){
                if(StringUtils.isNotEmpty(outfallTypeCode) && !"null".equals(outfallTypeCode)){
                    List<Map<String,Object>> rhoutDistributionColList=rhoutDistributionCol.get(outfallTypeCode);
                    Map<String,Object> outTypeMap=new HashMap<>();
                    outTypeMap.put("outfallTypeCode",outfallTypeCode);
                    outTypeMap.put("outfallTypeCodeName",rhoutDistributionColList.get(0).get("outfallName"));
                    outTypeMap.put("outfallNums",rhoutDistributionColList.size());
                    //按照河流分
                    Map<String,List<Map<String,Object>>>  rhoutRiverNameCol=rhoutDistributionColList.stream().collect(Collectors.groupingBy(s->String.valueOf(s.get("riverName"))));
                    List<Map<String,Object>> riverList=new ArrayList<>();
                    for(String riverName:rhoutRiverNameCol.keySet()){
                        if(StringUtils.isNotEmpty(riverName) && !"null".equals(riverName)){
                            List<Map<String,Object>>  rhoutRiverNameColList=rhoutRiverNameCol.get(riverName);
                            Map<String,Object> riverMap=new HashMap<>();
                            riverMap.put("name",riverName);
                            riverMap.put("nums",rhoutRiverNameColList.size());
                            riverList.add(riverMap);
                            if(!nameList.contains(riverName)){
                                nameList.add(riverName);
                            }
                        }
                    }
                    outTypeMap.put("valueList",riverList);
                    retList.add(outTypeMap);
                }
            }
        }else {//区县
            Map<String,List<Map<String,Object>>>  rhoutDistributionCol=rhoutDistributionList.stream().collect(Collectors.groupingBy(s->String.valueOf(s.get("outfallfirstclassifycode"))));
            for(String outfallTypeCode:rhoutDistributionCol.keySet()){
                if(StringUtils.isNotEmpty(outfallTypeCode) && !"null".equals(outfallTypeCode)){
                    List<Map<String,Object>> rhoutDistributionColList=rhoutDistributionCol.get(outfallTypeCode);
                    Map<String,Object> outTypeMap=new HashMap<>();
                    outTypeMap.put("outfallTypeCode",outfallTypeCode);
                    outTypeMap.put("outfallTypeCodeName",rhoutDistributionColList.get(0).get("outfallName"));
                    outTypeMap.put("outfallNums",rhoutDistributionColList.size());
                    //按照河流分
                    Map<String,List<Map<String,Object>>>  rhoutRiverNameCol=rhoutDistributionColList.stream().collect(Collectors.groupingBy(s->String.valueOf(s.get("countyCode"))));
                    List<Map<String,Object>> riverList=new ArrayList<>();
                    for(String countyCode:rhoutRiverNameCol.keySet()){
                        if(StringUtils.isNotEmpty(countyCode) && !"null".equals(countyCode)) {
                            List<Map<String, Object>> rhoutRiverNameColList = rhoutRiverNameCol.get(countyCode);
                            String county= String.valueOf(rhoutRiverNameColList.get(0).get("county"));
                            Map<String, Object> riverMap = new HashMap<>();
                            riverMap.put("name", county);
                            riverMap.put("nums", rhoutRiverNameColList.size());
                            riverList.add(riverMap);
                            if (!nameList.contains(county)) {
                                nameList.add(county);
                            }
                        }
                    }
                    outTypeMap.put("valueList",riverList);
                    retList.add(outTypeMap);
                }
            }
        }
        retMap.put("dataList",retList);
        retMap.put("nameList",nameList);
        return retMap;
    }
}
